package main

import (
	"fmt"
	"net"
	"strings"
	"time"
)

// UDP 服务器无需握手，监听后直接 ReadFromUDP 即可接收任意客户端的报文。
func main() {
	addr, err := net.ResolveUDPAddr("udp", "127.0.0.1:7070")
	if err != nil {
		panic(err)
	}

	conn, err := net.ListenUDP("udp", addr)
	if err != nil {
		panic(err)
	}
	defer conn.Close()

	buffer := make([]byte, 1024)

	fmt.Println("[udp-server] listening on 127.0.0.1:7070")

	for {
		// 读取单个 UDP 报文；返回对端地址
		n, remoteAddr, err := conn.ReadFromUDP(buffer)
		if err != nil {
			fmt.Println("[udp-server] read err:", err)
			continue
		}

		msg := strings.TrimSpace(string(buffer[:n]))
		fmt.Printf("[udp-server] from %s: %q\n", remoteAddr.String(), msg)

		var reply string
		switch strings.ToUpper(msg) {
		case "PING":
			reply = "PONG"
		case "TIME":
			reply = time.Now().Format("15:04:05")
		default:
			reply = "UPPER: " + strings.ToUpper(msg)
		}

		if _, err := conn.WriteToUDP([]byte(reply), remoteAddr); err != nil {
			fmt.Printf("[udp-server] write err to %s: %v\n", remoteAddr, err)
		}
	}
}
